package com.ruoyi.project.system.service.impl;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.system.domain.SiyuRecharge;
import com.ruoyi.project.system.mapper.SiyuRechargeMapper;
import com.ruoyi.project.system.mapper.SysUserMapper;
import com.ruoyi.project.system.service.ISiyuRechargeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * 充值记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-10-28
 */
@Service
public class SiyuRechargeServiceImpl implements ISiyuRechargeService {

    @Autowired
    private SiyuRechargeMapper siyuRechargeMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public int updatePayOrderStatus(Map<String, String> map) {
        String out_trade_no = map.get("out_trade_no");
        String total_fee = map.get("total_fee");
        String transaction_id = map.get("transaction_id");
        String openid = map.get("openid");
        String time_end = map.get("time_end");
        String userId = map.get("attach");

        // 1.判断是否处理
        SiyuRecharge siyuRecharge = siyuRechargeMapper.selectSiyuRechargeList(new SiyuRecharge(out_trade_no)).get(0);
        if ("1".equals(siyuRecharge.getStatus())) {
            return 2;
        }
        // 2.修改状态为已支付
        BigDecimal beforeBalance = sysUserMapper.selectUserById(siyuRecharge.getUserId()).getBalance();
        BigDecimal recharge = siyuRecharge.getRecharge();
        int rechargeSuccess = siyuRechargeMapper.updateSiyuRechargeSuccess(siyuRecharge.getId(), beforeBalance, beforeBalance.add(recharge));
        // 3.为商户充值余额
        rechargeSuccess += sysUserMapper.addBalance(siyuRecharge.getUserId(), recharge);
        return rechargeSuccess;
    }

    @Override
    public List<SiyuRecharge> selectSiyuRechargeList(SiyuRecharge siyuRecharge) {
        return siyuRechargeMapper.selectSiyuRechargeList(siyuRecharge);
    }

    @Override
    public int insertSiyuRecharge(SiyuRecharge siyuRecharge) {
        return siyuRechargeMapper.insertSiyuRecharge(siyuRecharge);
    }

}
